/*
 *    Copyright 2011 The gcal-to-refill project
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.googlecode.gcal2refill.controller.gcal2refill;

import java.io.IOException;
import java.io.OutputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

import javax.servlet.http.Cookie;


import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.StringUtil;

import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.googlecode.gcal2refill.PdfCreator;
import com.googlecode.gcal2refill.UserInput;

public class CreatePdfController extends Controller {
    @Override
    public Navigation run() throws Exception {
        String oauthTokenSecret = null;
        String accessToken = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for(Cookie cookie : cookies){
                if ("oauth_token_secret".equals(cookie.getName())){
                    oauthTokenSecret = cookie.getValue();
                }else if ("access_token".equals(cookie.getName())){
                    accessToken = cookie.getValue();
                }
            }
            UserInput ui = new UserInput();
            ui.setSelectedCalendar(request.getParameterValues("selectedCalendar[]"));
            ui.setHolidayCalendar(request.getParameterValues("holidayCalendar[]"));
            ui.setStartDate(asDate("startDate", "yyyy-MM-dd"));
            ui.setWeekPeriod(asInteger("weekPeriod"));
            ui.setVirticalStartTime(asInteger("virticalStartTime"));
            ui.setVirticalPeriod(asInteger("virticalPeriod"));
            ui.setSizeOfPaper(asInteger("sizeOfPaper"));
            String tojisiroChkBox = asString("tojisiro");
            ui.setTojisiro(!StringUtil.isEmpty(tojisiroChkBox));
            ui.setTojisiroSize(asInteger("tojisiroSize"));
            return createPdf(oauthTokenSecret,accessToken,ui);
        }
        return forward("index.jsp");
    }
    
    private Navigation createPdf(String oauthTokenSecret,String accessToken,UserInput ui){
        Properties props = new Properties();
        GoogleOAuthParameters params = new GoogleOAuthParameters();
        try {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            props.loadFromXML(cl.getResourceAsStream("gcal2refill_properties.xml"));
            params.setOAuthConsumerKey(props.getProperty("oauth.consumer.key"));
            params.setOAuthConsumerSecret(props.getProperty("oauth.consumer.secret"));
            params.setOAuthSignatureMethod("HMAC-SHA1");
            params.setOAuthTokenSecret(oauthTokenSecret);
            params.setOAuthToken(accessToken);
            OutputStream os = response.getOutputStream();
            PdfCreator creator = new PdfCreator();
            byte[] pdf = creator.createPdf(ui,params);
            response.setContentType("application/pdf");
            response.setContentLength(pdf.length);
            os = response.getOutputStream();
            os.write(pdf);
            os.close();
            return null;
        } catch (InvalidPropertiesFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return forward("index.jsp");
    }
}
